//
//  NetworkTools.swift
//  04-cocosPods-swift-封装AFN
//
//  Created by smartlei on 15/10/16.
//  Copyright © 2015年 smartlei. All rights reserved.
//

import UIKit
//使用OC的AFN需要自己导入头文件，并且头文件不加“.h”
import AFNetworking
//创建枚举
enum GCLRequestMethod: String {
    
    case GET = "GET"
    case POST = "POST"
}
//
//https://api.weibo.com/oauth2/authorize?client_id=2608467700&redirect_uri=http://www.baidu.com
class NetworkTools: AFHTTPSessionManager {
    //网络请求完成回调，类似于 OC 的 typeDefine
    typealias  GCLRequestCallBack = (result: AnyObject?,error: NSError?) -> ()
    // MARK - 应用appKey
    let AppKey = "2608467700"
    let AppSecret = "1a4880b87711dc9d4cdecc708b83ab95"
    let redirect_uri = "http://www.baidu.com"
    // MARK - 网络下载工具
    static let sharedTools: NetworkTools = {
        
        //由于继承的关系，可以使用父类的方法创建
        let tools = NetworkTools(baseURL: nil)
        //设置响应序列化解析器
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
    }()
    //获取用户的
    var access_tokenDict : [String: AnyObject]? {
        if let  access_token =  UserAccountViewModel.sharedUserAccountViewModel.access_token {
        return ["access_token": access_token]
        }
        return nil
    }
}
// MARk - 获取用户信息
extension NetworkTools{
    // MARK - 通过OAuth授权方式获取用户信息
    // -see []()
    /// - parameter uid:        需要查询的个性化域名,即授权用户的UID。
    /// - parameter access_token: 采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
    func loadUserInfo( uid: String,access_token: String,finished:GCLRequestCallBack){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let  parameters = ["uid": uid,"access_token":access_token]
        
        request(GCLRequestMethod.GET, URLString: urlString, parameters: parameters, finished: finished)
    }
    //MARK - 使用access_token获取用户信息列表
    //-see [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadStatus(finished: GCLRequestCallBack) {
        
        //1 判断access_token字典是否为nil
        guard let parame =  access_tokenDict else {
            
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -2000, userInfo: ["message": "access_tokenDict为nil"]))
        
            return
        }
        
        //2 准备URL
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //3 发送网络请求
        request(.GET, URLString: urlString, parameters: parame, finished: finished)
        
    }
}

// MARK: - 工具方法
extension NetworkTools {
    
    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    // MARK - 获取令牌
    func loadAccessToken(code: String,finished:GCLRequestCallBack) {
        
        let apiURL = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id": AppKey,
             "client_secret": AppSecret,
             "grant_type": "authorization_code",
             "code": code,
             "redirect_uri": redirect_uri,
        ]
        
     //   print(parameters)
        //调用类方法
        request(GCLRequestMethod.POST, URLString: apiURL, parameters: parameters, finished: finished)
    }

    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调
    func request(method: GCLRequestMethod, URLString: String ,parameters:[String: AnyObject]?,finished:GCLRequestCallBack){
        
        if method == GCLRequestMethod.GET {
            
            GET(URLString, parameters: parameters, success: { (_, result) -> Void in
                
                //成功回调
                finished(result: result, error: nil)
                
                }, failure: { (_, error) -> Void in
                
                    finished(result: nil, error: error)
            })
        }
        else{
            
            POST(URLString, parameters: parameters, success: { (_, result) -> Void in
                //成功回调
                finished(result: result, error: nil)
                
                }, failure: { (_, error) -> Void in
                    finished(result: nil, error: error)
            })     
        }
    }
    
}
